package com.erp.servlet;

import com.erp.bean.Emp;
import com.erp.bean.Role;
import com.erp.service.EmpService;
import com.erp.service.RoleService;
import com.erp.service.impl.RoleServiceImpl;
import com.erp.util.factroy.ObjectFactory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author lpy
 * 用户登录控制器
 */
@WebServlet("/login.action")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        EmpService empService = ObjectFactory.getServiceInstance("com.erp.service.impl.EmpServiceImpl",EmpService.class);
        //获取表单提交的用户信息
        String username = req.getParameter("username");
        String pass = req.getParameter("password");
        //获取用户输入的验证码
        String code = req.getParameter("captcha");
        //如果用户直接访问了login.action
        if (username==null&&pass==null&&code==null){
            //跳回登录页面
            resp.sendRedirect("login.jsp");
            return;
        }

        HttpSession session = req.getSession();
        //获取session中保存的验证码
        String seCode = (String) session.getAttribute("rand");
        if (seCode.equalsIgnoreCase(code)){
            //登录
            Emp emp = empService.findByNameAndPass(username,pass);
            if (emp!=null){
                RoleService roleService = new RoleServiceImpl();
//                IDeptService deptService = new DeptServiceImpl();
                Role role = roleService.findByRid(emp.getRid());
//                Dept dept = deptService.findById(emp.getDid());
               // List<Role> roles = roleService.findAll();
                //登录成功将用户信息、角色信息和部门信息、保存到session中,跳转到index.jsp
                session.setAttribute("currentUser",emp);
                //session.setAttribute("roles",roles);
                session.setAttribute("role",role);
                resp.sendRedirect("index.jsp");
            }else {
                req.setAttribute("errorMsg","账户或密码错误,请重新登录");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        }else {
            req.setAttribute("errorMsg","验证码输入错误,请重新输入");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
